#!/usr/bin/env python2.7

# bender.py

import os, sys
#import re
#from datetime import datetime, timedelta
#from dateutil.parser import parse
import numpy as np
import matplotlib
matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4']='PySide'
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

#from mpl_toolkits.basemap import Basemap
#from matplotlib import mlab
#from netCDF4 import Dataset
from PySide.QtCore import *
from PySide.QtGui import *
from ui_bender import *
from metlib.kits import Null

def curve2(x):
    return 1.0 - (x-1.0) ** 2

class Bender(QWidget, Ui_BenderWidget):
    def __init__(self, parent=None, func=curve2):
        super(Bender, self).__init__(parent)
        self.setupUi(self)
        self.bLabelHmin.setNum(self.hmin)
        self.bLabelH.setNum(self.h)
        self.bLabelXmin.setNum(self.xmin)
        self.applyButton.clicked.connect(self.update_fig)
        self.func = func
        self.fig = Figure(figsize=(1.5,2.0), dpi=96)
        self.ax  = self.fig.add_axes((0.0, 0.0, 1.0, 1.0))
        self.ax.set_xlim(0, 1)
        self.ax.set_ylim(0, 1)
        self.canvas = FigureCanvas(self.fig)
        self.figLayout.addWidget(self.canvas)
        
        self._fign = 20
        self.fighs = np.linspace(0, 1.0, self._fign)
        self.figline = self.ax.plot(self.figxs, self.fighs, 'k', lw=1.5)[0]
        self.canvas.draw()

        self.bSliderXmin.valueChanged.connect(self.update_fig)

    def update_fig(self, *args):
        self.figline.set_data(self.figxs, self.fighs)
        self.canvas.draw()
    
    def bend(self, data, heights):
        if self.on:
            xs = (heights - self.hmin) / self.h
            xs[xs > 1.0] = 1.0
            xs[xs < 0.0] = 0.0
            xs = xs * (1.0- self.xmin) + self.xmin
            bendratio = self.func(xs)
            return data * bendratio
        else:
            return data.copy()

    @property
    def hmin(self):
        return float(self.bSliderHmin.value())

    @hmin.setter
    def hmin(self, value):
        self.bSliderHmin.setValue(value)

    @property
    def h(self):
        return float(self.bSliderH.value())

    @h.setter
    def h(self, value):
        self.bSliderH.setValue(value)

    @property
    def xmin(self):
        return float(self.bSliderXmin.value()) / 100.0

    @xmin.setter
    def xmin(self, value):
        self.bSliderXmin.setValue(int(value*100.0))

    @property
    def figxs(self):
        return self.func(np.linspace(self.xmin, 1, self._fign))

    @property
    def on(self):
        return self.checkBox.isChecked()

    @on.setter
    def on(self, value):
        state = Qt.Checked if value else Qt.Unchecked
        self.checkBox.setCheckState(state)

if __name__ == '__main__':
    pass
